package tool

import (
	"crypto/md5"
	"encoding/hex"
	"hash/fnv"
	"math/rand"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo/v4"
)

type VisitUserInfo struct {
	UserName string
	Uid      int
	Platform string
}

var letters = []byte("0123456789abcdefghjkmnpqrstuvwxyz")

var r *rand.Rand

func init() {
	r = rand.New(rand.NewSource(time.Now().Unix()))
}
func IsExist(as []string, a string) bool {
	for _, v := range as {
		if v == a {
			return true
		}
	}
	return false
}

func GetUid(c echo.Context) int {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(jwt.MapClaims)
	uid := int(claims["id"].(float64))
	return uid
}

func MD5(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}

// Md5
func Md5(b []byte) string {
	h := md5.New()
	h.Write(b)
	return hex.EncodeToString(h.Sum(nil))
}

func GetUserName(c echo.Context) string {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(jwt.MapClaims)
	userName := claims["name"].(string)
	return userName
}

func GetHeaderPlatform(c echo.Context) string {
	platformId := c.Request().Header.Get("megaDataPlatform")
	switch platformId {
	case "0":

		return "Android"
	case "1":

		return "IOS"
	case "2":

		return "H5"
	}
	return "Unknown"
}

// 获得访问用户信息
func GetVisitUserInfo(c echo.Context) (u *VisitUserInfo) {

	u = new(VisitUserInfo)

	u.UserName = GetUserName(c)
	u.Uid = GetUid(c)
	u.Platform = GetHeaderPlatform(c)
	return
}

// 生成cdk
func CreateCdk(lens int) (cdk string) {
	if lens <= 0 {
		return
	}
	b := make([]byte, lens)
	arc := uint8(0)
	if _, err := r.Read(b[:]); err != nil {
		return
	}
	for i, x := range b {
		arc = x & 31
		b[i] = letters[arc]
	}
	return string(b)
}

// 字符串转数字
func StringToHashNum(s string) int {
	h := fnv.New32a()
	h.Write([]byte(s))
	return int(h.Sum32())
}

func RandomStr(n int) string {
	bytes := make([]byte, n)
	for i := 0; i < n; i++ {
		b := r.Intn(26) + 65
		bytes[i] = byte(b)
	}
	return string(bytes)
}
